{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from PIL import Image\n",
    "import json\n",
    "import os\n",
    "import time\n",
    "from glob import glob\n",
    "\n",
    "\n",
    "Classes = [\"D00\",\"D10\",\"D20\",\"D40\"]\n",
    "Names = [\"Czech\",\"India\",\"Japan\"]\n",
    "Box = [600,720,600]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def nms(dets, thresh):\n",
    "    x1 = dets[:, 0]\n",
    "    y1 = dets[:, 1]\n",
    "    x2 = dets[:, 2]\n",
    "    y2 = dets[:, 3]\n",
    "    scores = dets[:, 4]\n",
    "\n",
    "    areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n",
    "    order = scores.argsort()[::-1]\n",
    "\n",
    "    keep = []\n",
    "    while order.size > 0:\n",
    "        i = order[0]\n",
    "        keep.append(i)\n",
    "        xx1 = np.maximum(x1[i], x1[order[1:]])\n",
    "        yy1 = np.maximum(y1[i], y1[order[1:]])\n",
    "        xx2 = np.minimum(x2[i], x2[order[1:]])\n",
    "        yy2 = np.minimum(y2[i], y2[order[1:]])\n",
    "\n",
    "        w = np.maximum(0.0, xx2 - xx1 + 1)\n",
    "        h = np.maximum(0.0, yy2 - yy1 + 1)\n",
    "        inter = w * h\n",
    "        ovr = inter / (areas[i] + areas[order[1:]] - inter)\n",
    "\n",
    "        inds = np.where(ovr <= thresh)[0]\n",
    "        order = order[inds + 1]\n",
    "\n",
    "    return keep"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('ensemble1/base_model.json', 'r') as f:\n",
    "    D = json.load(f)\n",
    "\n",
    "\n",
    "Ensemble_D = {}\n",
    "\n",
    "\n",
    "mods = glob('ensemble1/model_*')\n",
    "\n",
    "for mod_idx in range(len(mods)):\n",
    "    with open(mods[mod_idx], 'r') as f:\n",
    "        Ensemble_D[mod_idx] = json.load(f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm \"ensemble1.txt\"\n",
    "con = [0.22,0.16,0.11]\n",
    "con3 = [0.7,0.7,0.6]\n",
    "con4 = [0.95,0.95,0.4]\n",
    "nm = [1,1,1]\n",
    "\n",
    "\n",
    "submission = list()\n",
    "dets = list()\n",
    "\n",
    "for count in range(len(D)):\n",
    "    line = list()\n",
    "    boxes = list()\n",
    "\n",
    "    name = D[count]['filename'].split(\"/\")[-1]\n",
    "    line.append(name)\n",
    "    idd = Names.index(name.split(\"_\")[0])\n",
    "\n",
    "    if (len(D[count]['objects']))!=0:\n",
    "        for bound in (D[count]['objects']):\n",
    "            if bound['confidence'] >=con[idd]:\n",
    "                idx = Classes.index(bound['name']) + 1\n",
    "                y = bound['relative_coordinates']['center_y']*Box[idd]\n",
    "                x = bound['relative_coordinates']['center_x']*Box[idd]\n",
    "                h = bound['relative_coordinates']['height']*Box[idd]*0.5\n",
    "                w = bound['relative_coordinates']['width']*Box[idd]*0.5\n",
    "\n",
    "                boxes.append([int(x-w),int(y-h),int(x+w),int(y+h),bound['confidence'],idx])\n",
    "    \n",
    "    for mod_idx in range(len(mods)):\n",
    "        if (len(Ensemble_D[mod_idx][count]['objects']))!=0:\n",
    "            for bound in (Ensemble_D[mod_idx][count]['objects']):\n",
    "                if bound['confidence'] >=con3[idd]:\n",
    "                    idx = Classes.index(bound['name']) + 1\n",
    "                    y = bound['relative_coordinates']['center_y']*Box[idd]\n",
    "                    x = bound['relative_coordinates']['center_x']*Box[idd]\n",
    "                    h = bound['relative_coordinates']['height']*Box[idd]*0.5\n",
    "                    w = bound['relative_coordinates']['width']*Box[idd]*0.5\n",
    "\n",
    "                    boxes.append([int(x-w),int(y-h),int(x+w),int(y+h),bound['confidence'],idx])\n",
    "    \n",
    "    \n",
    "    if len(boxes) > 0:\n",
    "        boxes = np.array(boxes).reshape(-1,6)            \n",
    "        ore = nms(boxes,nm[idd])\n",
    "        \n",
    "        for o in ore:\n",
    "            line.extend([boxes[o,5],boxes[o,0],boxes[o,1],boxes[o,2],boxes[o,3]])\n",
    "            \n",
    "\n",
    "    text_file = open(\"ensemble1.txt\", \"a\")\n",
    "    for a in line[0:1]:\n",
    "        text_file.write(str(a)+\",\")\n",
    "    dets.extend(line[1:])\n",
    "\n",
    "\n",
    "    for a in line[1:]:\n",
    "        text_file.write('%d' %a)\n",
    "        text_file.write(' ')\n",
    "\n",
    "    text_file.write(\"\\n\")\n",
    "    text_file.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('ensemble2/base_model.json', 'r') as f:\n",
    "    D = json.load(f)\n",
    "\n",
    "\n",
    "Ensemble_D = {}\n",
    "\n",
    "\n",
    "mods = glob('ensemble2/model_*')\n",
    "\n",
    "for mod_idx in range(len(mods)):\n",
    "    with open(mods[mod_idx], 'r') as f:\n",
    "        Ensemble_D[mod_idx] = json.load(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "!rm \"ensemble2.txt\"\n",
    "con = [0.22,0.16,0.11]\n",
    "con3 = [0.7,0.7,0.6]\n",
    "\n",
    "nm = [1,1,1]\n",
    "\n",
    "\n",
    "submission = list()\n",
    "dets = list()\n",
    "\n",
    "for count in range(len(D)):\n",
    "    line = list()\n",
    "    boxes = list()\n",
    "\n",
    "    name = D[count]['filename'].split(\"/\")[-1]\n",
    "    line.append(name)\n",
    "    idd = Names.index(name.split(\"_\")[0])\n",
    "\n",
    "    if (len(D[count]['objects']))!=0:\n",
    "        for bound in (D[count]['objects']):\n",
    "            if bound['confidence'] >=con[idd]:\n",
    "                idx = Classes.index(bound['name']) + 1\n",
    "                y = bound['relative_coordinates']['center_y']*Box[idd]\n",
    "                x = bound['relative_coordinates']['center_x']*Box[idd]\n",
    "                h = bound['relative_coordinates']['height']*Box[idd]*0.5\n",
    "                w = bound['relative_coordinates']['width']*Box[idd]*0.5\n",
    "\n",
    "                boxes.append([int(x-w),int(y-h),int(x+w),int(y+h),bound['confidence'],idx])\n",
    "    \n",
    "    for mod_idx in range(len(mods)):\n",
    "        if (len(Ensemble_D[mod_idx][count]['objects']))!=0:\n",
    "            for bound in (Ensemble_D[mod_idx][count]['objects']):\n",
    "                if bound['confidence'] >=con3[idd]:\n",
    "                    idx = Classes.index(bound['name']) + 1\n",
    "                    y = bound['relative_coordinates']['center_y']*Box[idd]\n",
    "                    x = bound['relative_coordinates']['center_x']*Box[idd]\n",
    "                    h = bound['relative_coordinates']['height']*Box[idd]*0.5\n",
    "                    w = bound['relative_coordinates']['width']*Box[idd]*0.5\n",
    "\n",
    "                    boxes.append([int(x-w),int(y-h),int(x+w),int(y+h),bound['confidence'],idx])\n",
    "    \n",
    "    \n",
    "    if len(boxes) > 0:\n",
    "        boxes = np.array(boxes).reshape(-1,6)            \n",
    "        ore = nms(boxes,nm[idd])\n",
    "        \n",
    "        for o in ore:\n",
    "            line.extend([boxes[o,5],boxes[o,0],boxes[o,1],boxes[o,2],boxes[o,3]])\n",
    "            \n",
    "\n",
    "    text_file = open(\"ensemble2.txt\", \"a\")\n",
    "    for a in line[0:1]:\n",
    "        text_file.write(str(a)+\",\")\n",
    "    dets.extend(line[1:])\n",
    "\n",
    "\n",
    "    for a in line[1:]:\n",
    "        text_file.write('%d' %a)\n",
    "        text_file.write(' ')\n",
    "\n",
    "    text_file.write(\"\\n\")\n",
    "    text_file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
